<template>
  <page-wrap :show-top="showTop" :bg-color="uNavColor" ref="pageWrap" hideTab back :title="title"
    :dark="loaded ? false : true" :hideSafeArea="true">
    <view class="info-confirm" :style="'padding-top:' + navHeight + 'px;'">
      <view class="consultant-info" :style="'height:' + consultantInfoHeight + 'rpx'">
        <view class="header">
          <view class="header-left">
            <image class="avatar" :src="consultantInfo.pic"></image>
          </view>
          <view class="header-right">
            <span class="name">{{ consultantInfo.iname }}</span>
            <view class="right-info">
              <span style="
                  width: 60rpx;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                ">{{ showAge }}岁</span>
              <view class="gray-column"></view>
              <span style="
                  width: 110rpx;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                ">
                {{ consultantInfo.personZw }}</span>
              <view class="gray-column"></view>
              <span style="
                  width: 60rpx;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                ">{{ consultantInfo.regionName }}</span>
            </view>
          </view>
        </view>
        <view class="good-at">
          <image class="logo" :src="goodAt"></image>
          <!-- 限制字符串长度自定义字符串长度最大为10 这里设置35 超过35就不展示 -->
          <view class="content">擅长：{{ showGoodAt }}</view>
        </view>
        <view class="foot" @click="changeButton" v-if="consultantInfo.goodAtList.length > 25">
          <view class="glass" v-if="buttonName === '展开'"></view>
          <view class="foot-button">
            <span>{{ buttonName }}</span>
            <u-icon :name="buttonIcon"></u-icon>
          </view>
        </view>
      </view>
      <view class="book-info">
        <u-form :model="form" ref="uForm" label-width="150rpx" :label-style="{ color: '#999999' }">
          <u-form-item v-if="currentType != 'check'" label="咨询日期" prop="askDate" right-icon="arrow-right"
            @click.native="goBack">
            <u-input v-model="form.askDate" disabled />
          </u-form-item>
          <u-form-item v-if="currentType == 'check'" label="咨询日期" prop="askDate" @click.native="goBack">
            <u-input v-model="form.askDate" disabled />
          </u-form-item>
          <u-form-item v-if="currentType != 'check'" label="咨询时间" prop="askTime" right-icon="arrow-right"
            @click.native="goBack">
            <u-input v-model="form.askTime" disabled />
          </u-form-item>
          <u-form-item v-if="currentType == 'check'" label="咨询时间" prop="askTime" @click.native="goBack">
            <u-input v-model="form.askTime" disabled />
          </u-form-item>
          <u-form-item v-if="currentType != 'check'" label="预约人" prop="bookPerson" right-icon="arrow-right"
            @click.native="goBack">
            <u-input v-model="form.bookPerson" disabled />
          </u-form-item>
          <u-form-item v-if="currentType == 'check'" label="预约人" prop="bookPerson" @click.native="goBack">
            <u-input v-model="form.bookPerson" disabled />
          </u-form-item>
          <u-form-item v-if="currentType != 'check'" label="手机号" prop="phone" right-icon="arrow-right">
            <u-input v-model="form.phone" maxlength="11" placeholder="请输入你的手机号码（必填）" :disabled="readonly" />
          </u-form-item>
          <u-form-item v-if="currentType == 'check'" label="手机号" prop="phone">
            <u-input v-model="form.phone" maxlength="11" placeholder="请输入你的手机号码（必填）" :disabled="readonly" />
          </u-form-item>
          <u-form-item v-if="currentType != 'check'" label="邮箱" prop="email" right-icon="arrow-right">
            <u-input v-model="form.email" placeholder="请输入你的邮箱（必填）" :disabled="readonly" />
          </u-form-item>
          <u-form-item v-if="currentType == 'check'" label="邮箱" prop="email">
            <u-input v-model="form.email" placeholder="请输入你的邮箱（必填）" :disabled="readonly" />
          </u-form-item>
        </u-form>
      </view>
      <view class="other-question">
        <span style="margin-bottom: 8rpx">填写咨询的问题(选填)</span>
        <view class="qusetionOptions" v-if="currentType === 'book'">
          <view v-for="(item, index) in questions" :key="index" @click="autoWrite(item)" class="options">
            {{ item }}
          </view>
        </view>
        <textarea style="margin-top: 24rpx; margin-bottom: 150rpx" :disabled="readonly" maxlength="1000"
          placeholder="填写咨询问题可以让顾问快速定位解决你的想要咨询的问题" v-model="form.otherQuestion" />
        <view class="operation">
          <u-button v-if="currentType === 'book'" type="primary" shape="circle" class="btn"
            @click="submit">提交</u-button>
          <u-button v-if="cancelavailable === 'true' && currentType === 'check'" shape="circle" class="btnCancel"
            @click="cancelAppointment" style="margin-right: 16rpx">取消预约</u-button>
          <u-button v-if="currentType === 'check' && isOverdue === 'false'" type="primary" shape="circle" class="btn"
            @click="toChat">去咨询顾问</u-button>
        </view>
      </view>
    </view>
  </page-wrap>
</template>

<script>
import { consultantInfo } from "@/api/modules/career";
import {
  addAppointment,
  getPersonAppointmentList,
  cancelAppointment,
  getPersonAppointmentInfo,
} from "@/api/index";

export default {
  components: {},
  data() {
    return {
      editionType: 10, // 是否是春风行动体验版 10正常版本 20体验版
      bookId: "",
      showAge: "",
      showGoodAt: "",
      uNavColor: "#ffffff",
      showTop: false,
      loaded: false,
      isOverdue: false,
      cancelavailable: false,
      questions: [
        "简历上亮点不够突出，简历通过率较低",
        "能力结合简历，无法体现自身价值与岗位的匹配度",
        "不知道去哪里找相关实习机会",
      ],
      bookMainId: "", // 预约主键id 用于取消预约
      showWebView: false,
      title: "预约顾问",
      readonly: false,
      currentType: "check", // 判断当前页面是第一次填写信息预约的还是回显 回显type就是check 第一次填写是book
      navHeight: getApp().globalData.navHeight,
      consultantInfoHeight: 310,
      consultantInfo: {
        pic: "",
        name: "jiang",
      },
      consultantId: "",
      goodAt: this.$imgBase + "career/careerAssessResult/goodAt.png",
      buttonName: "展开",
      buttonIcon: "arrow-down",
      form: {
        askDate: "",
        askTime: "",
        bookPerson: "", // 预约人姓名
        phone: "",
        email: "",
        otherQuestion: "",
        startTime: "",
        endTime: "",
      },
      rules: {
        // 字段名称
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.email(value);
            },
            message: "邮箱不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  onLoad(opt) {
    console.log("opt", opt);
    this.editionType = uni.getStorageSync("edition-Type");
    this.cancelavailable = opt.cancelavailable;
    this.isOverdue = opt.isOverdue;
    if (opt.isCheck) {
      this.bookId = opt.id;
      // 这里是查看填写信息逻辑
      console.log("这里是查看填写信息逻辑");
      this.readonly = true;
      this.currentType = "check";
      this.title = "预约信息";
      this.getPersonAppointmentInfo();
      if (opt.personId) {
        this.getPersonAppointmentInfo(opt.personId);
        console.log("opt.personId", opt.personId);
      }
    } else {
      // 这里是第一次预约逻辑
      this.readonly = false;
      this.currentType = "book";
      this.title = "预约信息确认";
      let info = JSON.parse(opt.info);
      console.log("info", info);
      this.form.startTime = info.startTime;
      this.form.endTime = info.endTime;
      this.form.askDate = info.startTime.slice(0, 10);
      this.form.askTime =
        info.startTime.slice(11, 16) + "-" + info.endTime.slice(11, 16);
      this.form.bookPerson = uni.getStorageSync("personName");
      console.log("this.form.bookPerson", this.form.bookPerson);
      this.consultantId = info.consultantId;
      console.log("this.consultantId", this.consultantId);
      this.consultantInfoFn();
    }
  },
  onShow() {},
  onHide() {},
  mounted() {},
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onPageScroll(res) {
    this.showTop = res.scrollTop > 0;
  },
  methods: {
    autoWrite(item) {
      if (this.readonly) {
        return;
      } else {
        this.form.otherQuestion = item;
      }
    },
    toChat() {
      uni.setStorageSync("consultantInfo", this.consultantInfo);
      console.log("这里点了去咨询顾问");
      // 是否登录im
      var isIMLogin =
        getApp().globalData.tim && getApp().globalData.tim.getLoginUser();
      if (!isIMLogin) {
        uni.showLoading({
          title: "正在连接",
          mask: true,
        });
        setTimeout(() => {
          uni.hideLoading();
        }, 5000);
        let isFirst = true;
        try {
          new IMEventHandler(() => {
            if (isFirst) {
              isFirst = false;
              uni.hideLoading();
              // this.reqZtBurryPoint({ rightId: "6", rightName: "顾问咨询" }); // 增加顾问咨询的埋点
              uni.navigateTo({
                // url: `/pagesSub/message/chat/index?chatId=${this.consultantInfo.consultantId}__consultant`,
                url: `/pagesSub/message/newChat/index?chatId=${this.consultantInfo.consultantId}_consultant&isZhituUser=1`,
              });
            }
          });
        } catch (error) {
          uni.hideLoading();
        }
      } else {
        // this.reqZtBurryPoint({ rightId: "6", rightName: "顾问咨询" }); // 增加顾问咨询的埋点
        uni.navigateTo({
          url: `/pagesSub/message/newChat/index?chatId=${this.consultantInfo.consultantId}_consultant&isZhituUser=1`,
        });
      }
    },
    async consultantInfoFn() {
      const params = {
        consultantId: parseInt(this.consultantId),
      };
      const res = await consultantInfo(params);
      if (res.code === 200) {
        this.consultantInfo = res.data;
        this.showAge =
          new Date().getFullYear() - this.consultantInfo.bday.slice(0, 4);
        this.showGoodAt = this.consultantInfo.goodAtList
          .join("、")
          .slice(0, 35);
        if (this.consultantInfo.goodAtList.length < 25) {
          this.consultantInfoHeight = 250;
        }
      }
    },
    changeButton() {
      if (this.buttonName === "展开") {
        this.buttonName = "收起";
        this.buttonIcon = "arrow-up";
        this.consultantInfoHeight = 350;
      } else {
        this.buttonName = "展开";
        this.buttonIcon = "arrow-down";
        this.consultantInfoHeight = 310;
      }
    },
    goBack() {
      if (this.currentType === "book") {
        uni.navigateBack();
      } else {
        return;
      }
    },
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          console.log("验证通过");
          uni.requestSubscribeMessage({
            tmplIds: [
              "-VgyrhPMJG8b_ZknZaBzNdTd5RqMQESZlZo3sMiiSFc",
              "z_G2uub-vdlGvYrJl6w8ZJX5LLYJBYtVYhEHIAVpodo",
            ],
            complete: (res) => {
              console.log("requestSubscribeMessage complete", res);
              this.addAppointment();
            },
          });
          //需要连接im然后给顾问发送一条已经预约的通知！
        } else {
          console.log("验证失败");
        }
      });
    },
    async addAppointment() {
      console.log(
        'uni.getStorageSync("edition-Type")',
        uni.getStorageSync("edition-Type")
      );
      const params = {
        consultantId: this.consultantId,
        personId: uni.getStorageSync("person-id").slice(2),
        appointmentStatus: 20,
        personPhone: this.form.phone,
        personEmail: this.form.email,
        personQuestion: this.form.otherQuestion,
        startTime: this.form.startTime,
        endTime: this.form.endTime,
        openId: uni.getStorageSync("openid"),
        editionType: uni.getStorageSync("edition-Type"),
      };
      const res = await addAppointment(params);
      if (res.code === 200) {
        uni.showToast({
          title: res.status_desc,
          icon: "none",
          duration: 1000
        });
        console.log("预约成功！");

        //预约成功后
        this.sendSingleTextMsg(
          `我已经预约您的咨询服务！
时间：${this.form.startTime}至${this.form.endTime}`
        );
        setTimeout(() => {
          uni.redirectTo({
            url: "/pagesSub/userCenter/careerPathV2/components/BookSuccess",
          });
        }, 1000);
      } else {
        uni.showToast({
          title: res.status_desc,
          icon: "none",
          duration: 1500,
        });
        setTimeout(() => {
          uni.redirectTo({
            url: "/pagesSub/userCenter/careerPathV2/components/BookSuccess?isFailed=true",
          });
        }, 1500);
      }
    },
    async getPersonAppointmentList() {
      const params = {
        pageNo: 1,
        pageSize: 999,
        personId: uni.getStorageSync("person-id").slice(2),
      };
      const res = await getPersonAppointmentList(params);
      if (res.code === 200) {
        this.consultantId = res.data[0].consultantId;
        this.consultantInfoFn();
        this.form.askDate = res.data[0].startTime.slice(0, 10);
        this.form.askTime =
          res.data[0].startTime.slice(11, 16) +
          "-" +
          res.data[0].endTime.slice(11, 16);
        this.form.phone = res.data[0].personPhone;
        this.form.email = res.data[0].personEmail;
        this.form.otherQuestion = res.data[0].personQuestion;
      }
    },
    async getPersonAppointmentInfo(personId) {
      const params = {
        personId: personId
          ? personId
          : uni.getStorageSync("person-id").slice(2),
        searchPersonInfo: true,
        id: this.bookId,
      };
      const res = await getPersonAppointmentInfo(params);
      if (res.code === 200) {
        this.bookMainId = res.data.id;
        this.consultantId = res.data.consultantId;
        this.consultantInfoFn();
        this.form.askDate = res.data.startTime.slice(0, 10);
        this.form.askTime =
          res.data.startTime.slice(11, 16) +
          "-" +
          res.data.endTime.slice(11, 16);
        this.form.phone = res.data.personPhone;
        this.form.email = res.data.personEmail;
        this.form.bookPerson = res.data.personName;
        this.form.otherQuestion =
          res.data.personQuestion == ""
            ? "未填写咨询问题～"
            : res.data.personQuestion;
      }
    },
    async cancelAppointment() {
      const params = {
        id: this.bookMainId,
        personId: uni.getStorageSync("person-id").slice(2),
      };
      const res = await cancelAppointment(params);
      if (res.code === 200) {
        uni.showToast({
          title: res.status_desc,
          icon: "none",
          duration: 1500,
        });
        // 取消预约
        this.sendSingleTextMsg(
          `我已取消和您预约的咨询服务！
时间：${this.form.askDate} ${this.form.askTime.slice(0, 5)}:00 至 ${
            this.form.askDate
          } ${this.form.askTime.slice(6)}:00`
        );
      } else {
        uni.showToast({
          title: res.status_desc,
          icon: "none",
          duration: 1500,
        });
      }
      setTimeout(() => {
        uni.redirectTo({
          url: "/pagesSub/userCenter/careerPathV2/index",
        });
      }, 1500);
    },
    // 发送单聊文本消息(第一步)
    sendSingleTextMsg(text) {
      console.log("发送消息：", text);

      var idate = new Date().getTime();
      let msg = {
        send_uid: this.personId,
        receive_uid: this.consultantId + "_consultant",
        content: text,
        // person_iname: this.selfInfo.info.nickname,
        // person_pic: this.selfInfo.info.extras.GET_PIC,
        is_send: "1",
        idate: idate,
        type: 1,
      };

      // console.log("sendSingleTextMsg", msg);
      this.createMsgContent(msg);
    },
    //创建消息体并调用IM发送（第二步）
    createMsgContent(content) {
      // console.log("createMsgContent", content);

      const that = this;
      let _self = this;
      var isIMLogin =
        getApp().globalData.tim && getApp().globalData.tim.getLoginUser();
      if (!isIMLogin || !isConnect) {
        new IMEventHandler(() => {
          uni.hideLoading();
          that.creatMsgContent(content);
        });
        return uni.showLoading({
          title: "正在连接",
          mask: true,
        });
      }
      if (!content) {
        return uni.showToast({
          icon: "none",
          title: "发送内容不能为空",
        });
      }

      content = JSON.stringify(content);
      //目标username改一下
      const params = {
        target_username: this.consultantId + "_consultant",
        content: content,
        no_offline: false,
        no_notification: false,
        // custom_notification: {
        //   enabled: true,
        //   title: this.selfInfo.info.extras.Get_Person_Iname,
        //   alert: JSON.parse(content).content,
        // },
        need_receipt: true,
      };
      // console.log("createMsgContent params", params);

      getApp()
        .globalData.tim.sendSingleMsg(params)
        .onSuccess(function (data, msg) {
          console.log("发送信息成功", data, msg);
          _self.handleSendMsgSuccess(data, msg);
        })
        .onFail((data) => {
          console.log("发送信息失败，", data);
          switch (data.code) {
            case 880207:
              uni.showToast({
                title: "发送消息失败，已被对方拉入黑名单!",
                icon: "none",
              });
              break;
            case 880103:
              _self.register(_self.chatId);
              break;
            default:
              uni.showToast({
                icon: "none",
                title: "打招呼消息发送失败",
              });
              _self.reportImLog({
                data,
                params: params,
                selfinfo: _self.selfInfo,
                source: "mp",
              });
              break;
          }
        });
    },
    // 成功发送消息处理，发完还要给本地消息记录插入一条，否者在message.index里不会显示
    handleSendMsgSuccess(data, msg) {
      msg.ctime_ms = data.ctime_ms;
      let msgList = getApp().globalData.messageList.filter(
        (ele) => ele.from_username == this.consultantId + "_consultant"
      );
      if (!msgList.length) {
        let msgItem = {
          from_username: msg.target_name,
          msgs: [msg],
        };
        getApp().globalData.messageList.push(msgItem);
      } else {
        msgList[0].msgs.push(msg);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
$img-base-person: $img-base + "careerPath/";
.info-confirm {
  width: 100%;
  background-image: url($img-base + "careerPath/consultantHallBg.png?v=2");
  background-size: 100% auto;
  background-repeat: no-repeat;
  background-color: #fff5ea;
  padding: 16rpx;
  .consultant-info {
    background-color: #ffffff;
    border-radius: 25rpx;
    position: relative;
    overflow-y: hidden;
    .header {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 28rpx;
      .header-left {
        .avatar {
          width: 128rpx;
          height: 128rpx;
          border-radius: 50%;
        }
      }
      .header-right {
        display: flex;
        flex-direction: column;
        height: 120rpx;
        justify-content: space-around;
        margin-left: 28rpx;
        .name {
          width: 200rpx;
          height: 36rpx;
          font-size: 40rpx;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          color: #222222;
          line-height: 36rpx;
        }
        .right-info {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
          font-size: 26rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          color: #555555;
          .gray-column {
            width: 2rpx;
            height: 28rpx;
            background: #e6e6e6;
            margin: 0 20rpx;
          }
        }
      }
    }
    .good-at {
      padding: 0 24rpx;
      display: flex;
      .logo {
        width: 36rpx;
        height: 36rpx;
      }
      .content {
        width: 85vw;
        margin-left: 14rpx;
      }
    }
    .foot {
      width: 100%;
      position: absolute;
      bottom: 0;
      padding-bottom: 18rpx;
      .glass {
        width: 100%;
        height: 66rpx;
        background: linear-gradient(
          180deg,
          rgba(255, 255, 255, 0) 0%,
          #ffffff 100%
        );
      }
      .foot-button {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        color: #999999;
        span {
          margin-right: 6rpx;
          font-size: 24rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
        }
      }
    }
  }
  .book-info {
    background-color: #ffffff;
    border-radius: 25rpx;
    margin-top: 16rpx;
    ::v-deep .u-input__input {
      text-align: right;
      font-size: 30rpx !important;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #222222 !important;
    }
    ::v-deep.u-form-item {
      width: 90vw;
      margin: 0 auto;
    }
    ::v-deep .u-form-item__message {
      text-align: right;
    }
  }
  .other-question {
    background-color: #ffffff;
    border-radius: 25rpx;
    margin-top: 16rpx;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .qusetionOptions {
      width: 90vw;
      .options {
        padding: 0 20rpx;
        height: 56rpx;
        border-radius: 200rpx;
        border: 2rpx solid #dbdbdb;
        color: #666666;
        margin-top: 16rpx;
        display: flex;
        align-items: center;
        justify-content: flex-start;
      }
    }
    span {
      font-size: 30rpx;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      color: #333333;
    }
    textarea {
      background: #f6f6f6;
      width: 100%;
      height: 500rpx;
      padding: 24rpx;
      box-sizing: border-box;
    }
    .operation {
      width: 100%;
      display: flex;
      justify-content: center;
      padding: 0 32rpx;
      position: fixed;
      padding-bottom: calc(5rpx + constant(safe-area-inset-bottom));
      padding-bottom: calc(5rpx + env(safe-area-inset-bottom));
      bottom: 0;
      left: 0;
      z-index: 999;
      .btnCancel {
        width: 240rpx;
        ::v-deep .u-btn--default {
          color: #ffffff;
          border-color: #b7b7b7;
          background-color: #b7b7b7;
          font-weight: bold;
        }
      }
      .btn {
        width: 100%;
        font-weight: bold;
      }
    }
  }
}
</style>
